import re
import threading
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, colors
from pubsub import pub

from 文档自动填写GUI程序.common import split_string_by_multiple_delimiters

'''
成孔检查记录处理
'''


class RecordThread(threading.Thread):
    def __init__(self, path, piler_no):
        super().__init__()
        self.path = path
        self.piler_no = piler_no

    def run(self) -> None:
        try:
            self.get_data()
        except Exception as e:
            pub.sendMessage('error_status', message=e)

    def get_data(self):
        path = self.path
        no = self.piler_no
        delimiters = [',', ';', '，', '；', '\n']
        piler_no_list = split_string_by_multiple_delimiters(no, delimiters)
        template = "./钻孔桩成孔质量检查记录模板.xlsx"
        df = pd.read_excel(path, sheet_name="检查记录")
        for piler_no in piler_no_list:
            flag = 0
            piler_no = re.sub(r"\s+", "", piler_no)
            if piler_no is None or piler_no == "":
                return
            for index, row in df.iterrows():
                if str(row["桩号"]).lower() == piler_no.lower():
                    height = row["实际桩底标高"]
                    if pd.isna(height):
                        pub.sendMessage('info_status', message='桩基数据错误，请检查该桩号' + row["桩号"] + "的数据")
                    else:
                        write_excel(template, row)
                    flag = 1

            if flag == 0:
                pub.sendMessage('info_status', message='该桩号' + piler_no + "数据不存在!")


def write_excel(path, data):
    piler_no = data["桩号"]
    wb = load_workbook(path)
    sheet = wb.active
    sheet["F8"] = str(data["墩台编号"])
    sheet["L8"] = data["桩号"]
    sheet["T8"] = str(data["孔垂直度"]) + "%"
    sheet["F9"] = data["护筒顶高度"]
    sheet["N9"] = data["设计桩底标高"]
    sheet["F10"] = data["桩径"]
    sheet["N10"] = data["实际桩底标高"]
    sheet["F11"] = data["成孔直径"]
    sheet["N11"] = data["灌注前孔底标高"]
    sheet["S11"] = data["前"]
    sheet["U11"] = data["后"]
    sheet["X11"] = data["左"]
    sheet["AA11"] = data["右"]
    sheet["K17"] = data["骨架总长"]
    total_length = data["骨架总长"]
    num = total_length // 9
    s = ""
    for i in range(0, int(num)):
        s += "9 + "
    s += str(total_length % 9)
    sheet["K18"] = s

    # 设置字体样式
    font = Font(name='华文行楷', size=30, bold=False, color=colors.BLACK)
    sheet["F12"] = "无"
    sheet.cell(12, 6).font = font

    font1 = Font(name='华文行楷', size=28, bold=False, color=colors.BLACK)
    sheet["F19"] = "符合设计及规范要求"
    sheet.cell(19, 6).font = font1
    file_name = piler_no + ".钻孔桩成孔质量检查记录.xlsx"
    pub.sendMessage('info_status', message=file_name + '    ----->文件生成完毕')
    full_path = "./out/" + file_name
    wb.close()
    wb.save(full_path)
